<script setup lang="ts">
// 引入 Vue 的 Composition API
import {ref, onMounted, onBeforeUnmount, watch, nextTick} from 'vue'
// 引入 echarts 库
import * as echarts from 'echarts'

const radio1 = ref('Bar')
// 获取 DOM 元素的引用（用于初始化图表）
const chartRef = ref(null)
const lineChartRef = ref(null)
// 存储 ECharts 实例
let chartInstance: echarts.ECharts | null = null
let lineChartInstance: echarts.ECharts | null = null

// 初始化柱状图的方法
const initChart = () => {
  if (chartRef.value) {
    // 初始化 echarts 实例
    chartInstance = echarts.init(chartRef.value)

    // 配置项
    const option = {
      title: {
        text: 'Fly Bar' // 图表标题
      },
      tooltip: {}, // 默认提示框配置
      legend: {
        data: ['访问量'] // 图例名称
      },
      xAxis: {
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'] // X 轴数据
      },
      yAxis: {}, // Y 轴默认配置
      series: [
        {
          name: '访问量', // 系列名称
          type: 'bar', // 图表类型为柱状图
          data: [3000, 2000, 3333, 5000, 3200, 2000, 4000, 5000, 6000, 7000, 8000, 9000] // 数据值
        }
      ]
    }

    // 使用配置项渲染图表
    chartInstance.setOption(option)
  }
}

// 初始化折线图的方法
const initLineChart = () => {
  if (lineChartRef.value) {
    lineChartInstance = echarts.init(lineChartRef.value)

    const option = {
      color: ['#80FFA5', '#00DDFF', '#37A2FF', '#FF0087', '#FFBF00'],
      title: {
        text: 'Fly Line'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        }
      },
      legend: {
        data: ['Line 1', 'Line 2', 'Line 3', 'Line 4', 'Line 5']
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: 'Line 1',
          type: 'line',
          stack: 'Total',
          smooth: true,
          lineStyle: {
            width: 0
          },
          showSymbol: false,
          areaStyle: {
            opacity: 0.8,
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgb(128, 255, 165)'
              },
              {
                offset: 1,
                color: 'rgb(1, 191, 236)'
              }
            ])
          },
          emphasis: {
            focus: 'series'
          },
          data: [140, 232, 101, 264, 90, 340, 250]
        },
        {
          name: 'Line 2',
          type: 'line',
          stack: 'Total',
          smooth: true,
          lineStyle: {
            width: 0
          },
          showSymbol: false,
          areaStyle: {
            opacity: 0.8,
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgb(0, 221, 255)'
              },
              {
                offset: 1,
                color: 'rgb(77, 119, 255)'
              }
            ])
          },
          emphasis: {
            focus: 'series'
          },
          data: [120, 282, 111, 234, 220, 340, 310]
        }
      ]
    }

    lineChartInstance.setOption(option)
  }
}

// 销毁柱状图实例
const disposeChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
}

// 销毁折线图实例
const disposeLineChart = () => {
  if (lineChartInstance) {
    lineChartInstance.dispose()
    lineChartInstance = null
  }
}

// 窗口大小变化时调整图表尺寸
const resizeChart = () => {
  chartInstance?.resize()
  lineChartInstance?.resize()
}

// 组件挂载后执行初始化
onMounted(() => {
  initChart()
  initLineChart()
  // 监听窗口大小变化事件以支持响应式
  window.addEventListener('resize', resizeChart)
})

// 组件卸载前清理资源，防止内存泄漏
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  disposeChart()
  disposeLineChart()
})

// 监听 radio1 变化，切换后初始化或销毁图表
watch(radio1, (newVal) => {
  nextTick(() => {
    if (newVal === 'Bar') {
      // 销毁折线图实例
      disposeLineChart()
      // 初始化柱状图
      if (!chartInstance) {
        initChart()
      }
    } else if (newVal === 'Line') {
      // 销毁柱状图实例
      disposeChart()
      // 初始化折线图
      if (!lineChartInstance) {
        initLineChart()
      }
    }
  })
})
</script>

<template>
  <div class="charts">
    <!-- 图表容器：设置宽度和高度 -->
    <div style="margin-top: 10px;margin-bottom: 20px">
      <el-radio-group v-model="radio1">
        <el-radio-button label="Bar" value="Bar"/>
        <el-radio-button label="Line" value="Line"/>
      </el-radio-group>
    </div>
    <div v-if="radio1 === 'Bar'" class="charts1" ref="chartRef" style="width: 100%; height:400px;"></div>
    <div v-if="radio1 === 'Line'" class="charts2" ref="lineChartRef" style="width: 100%; height:400px;"></div>
  </div>
</template>

<style scoped>
.charts {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  margin-top: 30px;
}
</style>
